package com.zidian.teacher.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.PopupMenu;

import com.google.gson.Gson;
import com.zidian.teacher.R;
import com.zidian.teacher.adapter.ListGroupAdapter;
import com.zidian.teacher.bean.ListGroupBean;
import com.zidian.teacher.bean.PutGroupBean;
import com.zidian.teacher.utils.GetUserInfo;
import com.zidian.teacher.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

import com.zidian.teacher.adapter.ListStudyAdapter;
import com.zidian.teacher.bean.GroupListBean;
import com.zidian.teacher.bean.ListStudyBean;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.common.ToolBarActivity;

/**
 * Created by Administrator on 2016/9/6 0006.
 */
public class TeachingStudentListActivity extends ToolBarActivity {

    @Bind(R.id.group_recycler)
    RecyclerView groupRecycler;
    @Bind(R.id.study_recycler)
    RecyclerView studyRecycler;
    private ImageButton manageMenu;
    private ListGroupAdapter groupAdapter;
    private ListStudyAdapter studyAdapter;
    private LinearLayoutManager mGroupLayoutManager;
    private LinearLayoutManager mStudyLayoutManager;
    private String courseId;

    private int oldSelectedPosition = 0;
    private PutGroupBean groupBeans = new PutGroupBean();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_add);
        setContentView(R.layout.activity_teaching_study_list);
        setTitle("学员列表");
        ButterKnife.bind(this);
//        confrimBtn = (TextView) findViewById(R.id.toolbar_sure);
//        confrimBtn.setText("保存");
        manageMenu = (ImageButton) findViewById(R.id.toolbar_add);
        courseId = getIntent().getStringExtra("courseId");
        manageMenu.setImageResource(R.drawable.icon_more_horiz);
        getGroupMessage();
        initView();

    }

    private void initView() {

        groupAdapter = new ListGroupAdapter(this, groupBeanList);
        studyAdapter = new ListStudyAdapter(this, groupBeanList);

        mGroupLayoutManager = new LinearLayoutManager(this);
        mStudyLayoutManager = new LinearLayoutManager(this);

        groupRecycler.setLayoutManager(mGroupLayoutManager);
        studyRecycler.setLayoutManager(mStudyLayoutManager);

        groupRecycler.setAdapter(groupAdapter);
        studyRecycler.setAdapter(studyAdapter);


        groupAdapter.setOnItemClickListener(new ListGroupAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                changeSelected(position);


            }

            @Override
            public void onItemLongClick(View view, int position) {


            }
        });


        studyAdapter.setOnItemClickListener(new ListStudyAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(View view, int position, String studentId,String sutdentName) {
                Intent intent = new Intent();
                intent.setClass(TeachingStudentListActivity.this, StudentDetailActivity.class);
                intent.putExtra("courseId", courseId);
                intent.putExtra("studentId", studentId);
                intent.putExtra("studentName",sutdentName);
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

        manageMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popup = new PopupMenu(TeachingStudentListActivity.this, manageMenu);

                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        Intent intent = new Intent();
                        switch (item.getItemId()) {
                            case R.id.group_manage:
                                groupBeans.setGroupBeans(groupBeanList);
                                intent.setClass(TeachingStudentListActivity.this, GroupManageActivity.class);
                                intent.putExtra("groupBeans", groupBeans);
                                intent.putExtra("courseId", courseId);
                                startActivityForResult(intent, 5000);
                                break;
                            case R.id.grades:
                                intent.setClass(TeachingStudentListActivity.this, StudentResultActivity.class);
                                intent.putExtra("courseId", courseId);
                                startActivity(intent);
                                break;
                        }
                        return true;
                    }
                });
                //使用反射，强制显示菜单图标
                try {
                    Field[] fields = popup.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        if ("mPopup".equals(field.getName())) {
                            field.setAccessible(true);
                            Object menuPopupHelper = field.get(popup);
                            Class<?> classPopupHelper = Class.forName(menuPopupHelper
                                    .getClass().getName());
                            Method setForceIcons = classPopupHelper.getMethod(
                                    "setForceShowIcon", boolean.class);
                            setForceIcons.invoke(menuPopupHelper, true);
                            break;
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                popup.inflate(R.menu.menu_main);
                popup.show();
            }
        });


    }


    private void changeSelected(int position) {
        groupBeanList.get(oldSelectedPosition).setIsSelect(false);
        groupBeanList.get(position).setIsSelect(true);
        //增加左侧联动
//        groupRecycler.scrollToPosition(position);
        oldSelectedPosition = position;
        studyAdapter.setGroupList(groupBeanList);
        groupAdapter.notifyDataSetChanged();
        studyAdapter.notifyDataSetChanged();
    }


    private List<ListGroupBean> groupBeanList = new ArrayList<>();

    private void initData(GroupListBean model) {

        List<ListStudyBean> all = new ArrayList<>();

        for (int i = 0; i < model.getData().size(); i++) {
            List<ListStudyBean> group = new ArrayList<>();
            if (model.getData().get(i).getGroup() != null)
                if (model.getData().get(i).getGroup().size() == 0) {
                    continue;
                }
                for (int j = 0; j < model.getData().get(i).getGroup().size(); j++) {
                    group.add(new ListStudyBean(model.getData().get(i).getGroup().get(j).getStudentHeadPortrait(), model.getData().get(i).getGroup().get(j).getStudentName(), model.getData().get(i).getGroup().get(j).getStudentId(), model.getData().get(i).getGroup().get(j).getGroupId(), false));
                }
            all.addAll(group);
            ListGroupBean g = new ListGroupBean(model.getData().get(i).getGroupingName(), group.size() + "", model.getData().get(i).getGroupingId(), false, group);
            groupBeanList.add(g);
        }
        ListGroupBean allG = new ListGroupBean("全部", all.size() + "", "0", true, all);
        groupBeanList.add(0, allG);
        studyAdapter.setGroupList(groupBeanList);
        groupAdapter.notifyDataSetChanged();
        studyAdapter.notifyDataSetChanged();


    }


    private void getGroupMessage() {

        String loginUrl = Constant.URL_GOAL + "work/student";
        HashMap<String, String> map = new HashMap<>();
        map.put("courseId", courseId);
        map.put("teacherId", GetUserInfo.getTeacherId(context));
        map.put("className", "");
        map.put("token", GetUserInfo.getToken(context));


        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.showToast(context, "获取列表失败！");
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        Log.e("TAG",jsonObject.getString("message"));
                        return;
                    }
                } catch (JSONException e) {

                }

                Gson gson = new Gson();
                GroupListBean model = gson.fromJson(response, GroupListBean.class);
                if (model.isSuccess()) {
                    initData(model);
                }

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 5000) {
            if (resultCode == 5001) {
                boolean hasChange = data.getBooleanExtra("hasChange", false);
                if (hasChange) {
                    groupBeanList.clear();
                    getGroupMessage();
                }
            }
        }

    }
}
